<?php

namespace Illuminate\Filesystem;

use Illuminate\Contracts\Cache\Repository;
use League\Flysystem\Cached\Storage\AbstractCache;

/**
 * Laravel 系统基于 League\Flysystem 缓存实现的专用扩展
 */
class Cache extends AbstractCache
{
    /**
     * 缓存服务实例
     *
     * @var \Illuminate\Contracts\Cache\Repository
     */
    protected $repository;

    /**
     * 缓存键名
     *
     * @var string
     */
    protected $key;

    /**
     * 缓存过期时间（以秒为单位）
     *
     * @var int|null
     */
    protected $expire;

    /**
     * 创建一个新的缓存实例
     *
     * @param  \Illuminate\Contracts\Cache\Repository $repository
     * @param  string $key
     * @param  int|null $expire
     * @return void
     */
    public function __construct(Repository $repository, $key = 'flysystem', $expire = null)
    {
        $this->key = $key;
        $this->expire = $expire;
        $this->repository = $repository;
    }

    /**
     * 装载数据到缓存中
     *
     * @return void
     */
    public function load()
    {
        $contents = $this->repository->get($this->key);

        if (!is_null($contents)) {
            $this->setFromStorage($contents);
        }
    }

    /**
     * 保留缓存数据
     *
     * @return void
     */
    public function save()
    {
        $contents = $this->getForStorage();

        $this->repository->put($this->key, $contents, $this->expire);
    }
}
